// 获取页面元素
const rdpForm = document.getElementById('rdpForm');
const errorMessages = document.getElementById('errorMessages');
const canvas = document.getElementById('rdpCanvas');
const ctx = canvas.getContext('2d');
const controlButtons = document.getElementById('controlButtons');
const disconnectButton = document.getElementById('disconnectButton');
const pasteButton = document.getElementById('pasteButton');
const resolutionButton = document.getElementById('resolutionButton');
const loadingOverlay = document.getElementById('loadingOverlay');
const keyboardToggle = document.getElementById('keyboardToggle');
const floatBall = document.getElementById('floatBall');
const disconnectButtonFloat = document.getElementById('disconnectButtonFloat');
const pasteButtonFloat = document.getElementById('pasteButtonFloat');
const resolutionButtonFloat = document.getElementById('resolutionButtonFloat');
const exitFullscreenButton = document.getElementById('exitFullscreenButton');
const virtualKeyboard = document.getElementById('virtualKeyboard');
const keyboardInput = document.getElementById('keyboardInput');

// WebSocket连接对象
let ws;

// 连接到WebSocket服务
function connectWebSocket(serverAddress, serverPort, username, password) {
    ws = new WebSocket(`wss://${window.location.hostname}:8081/connect?server=${serverAddress}&port=${serverPort}&username=${username}&password=${password}`);

    ws.onopen = () => {
        console.log('已连接到RDP服务器');
        rdpForm.style.display = 'none';
        canvas.style.display = 'block';
        controlButtons.style.display = 'flex';
        keyboardToggle.style.display = 'block';
    };

    ws.onmessage = (event) => {
        const data = new Uint8Array(event.data);
        const img = new Image();
        img.src = URL.createObjectURL(new Blob([data], { type: 'image/png' }));
        img.onload = () => {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
        };

        // 处理分辨率更改确认消息
        const message = JSON.parse(event.data);
        if (message.type ==='resolution_confirm') {
            loadingOverlay.style.display = 'none';
        }
    };

    ws.onclose = () => {
        console.log('已断开与RDP服务器的连接');
        rdpForm.style.display = 'block';
        canvas.style.display = 'none';
        controlButtons.style.display = 'none';
        keyboardToggle.style.display = 'none';
        floatBall.style.display = 'none';
        virtualKeyboard.style.display = 'none';
    };

    ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        if (error instanceof DOMException && error.name === 'WebSocketError') {
            errorMessages.innerHTML += '<p>WebSocket连接失败，请检查网络连接或服务器是否正常运行。</p>';
        } else if (error.code === 'ECONNREFUSED') {
            errorMessages.innerHTML += '<p>服务器拒绝连接，请检查服务器地址和端口是否正确。</p>';
        } else {
            errorMessages.innerHTML += `<p>WebSocket连接错误: ${error.message}，请尝试重新连接或联系管理员。</p>`;
        }
    };
}

// 捕获键盘事件
function handleKeydown(event) {
    if (ws) {
        ws.send(JSON.stringify({ type: 'keydown', key: event.key }));
    }
}
window.addEventListener('keydown', handleKeydown);

// 键盘唤起按钮点击事件
function handleKeyboardToggleClick() {
    keyboardInput.focus();
    virtualKeyboard.style.display = 'block';
    // 适当上移页面内容，避免虚拟键盘遮挡
    document.body.style.paddingBottom = virtualKeyboard.offsetHeight + 'px';
    console.log('唤起键盘');
}
keyboardToggle.addEventListener('click', handleKeyboardToggleClick);

// 定义按键映射，用于组合键等功能
const keyMap = {
    'Ctrl': false,
    'Shift': false,
    'Alt': false
};

// 虚拟键盘按钮点击事件处理函数
function handleVirtualKeyboardButtonClick(event) {
    const key = event.target.textContent;
    const isModifier = ['Ctrl', 'Shift', 'Alt'].includes(key);

    if (isModifier) {
        keyMap[key] =!keyMap[key];
        return;
    }

    if (key === 'Enter') {
        if (keyMap.Ctrl) {
            // 处理Ctrl + Enter组合键，例如发送换行符
            if (ws) {
                ws.send(JSON.stringify({ type: 'keydown', key: '\n' }));
            }
        } else {
            if (ws) {
                ws.send(JSON.stringify({ type: 'keydown', key: key }));
            }
        }
    } else if (key === 'C' && keyMap.Ctrl) {
        // 处理Ctrl + C组合键，模拟复制操作
        if (navigator.clipboard) {
            navigator.clipboard.readText().then(text => {
                if (ws) {
                    ws.send(JSON.stringify({ type: 'paste', text: text }));
                }
            }).catch(err => {
                console.error('复制失败:', err);
            });
        } else {
            console.log('您的浏览器不支持复制操作，请升级浏览器。');
        }
    } else if (key === 'V' && keyMap.Ctrl) {
        // 处理Ctrl + V组合键，模拟粘贴操作
        if (navigator.clipboard) {
            navigator.clipboard.readText().then(text => {
                if (ws) {
                    ws.send(JSON.stringify({ type: 'paste', text: text }));
                }
            }).catch(err => {
                console.error('粘贴失败:', err);
            });
        } else {
            console.log('您的浏览器不支持粘贴操作，请升级浏览器。');
        }
    } else {
        if (ws) {
            ws.send(JSON.stringify({ type: 'keydown', key: key }));
        }
    }
}

// 创建虚拟键盘按钮并添加到虚拟键盘容器中
const baseKeys = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
    'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
    'Z', 'X', 'C', 'V', 'B', 'N', 'M',' ',
    '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
    'Enter', 'Backspace', 'Tab', 'Shift', 'Ctrl', 'Alt',' '
];

const functionKeys = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'];
const symbolKeys = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '+', '[', ']', '{', '}', '|', ';', ':', '\'', ',', '<', '.', '>', '/', '?'];

function createKeyboardLayout(keys) {
    keys.forEach(key => {
        const button = document.createElement('button');
        button.textContent = key;
        button.addEventListener('click', handleVirtualKeyboardButtonClick);
        // 添加按钮按下时的视觉反馈
        button.addEventListener('mousedown', () => button.style.backgroundColor = '#005a9e');
        button.addEventListener('mouseup', () => button.style.backgroundColor = '#0078d7');
        virtualKeyboard.appendChild(button);
    });
}

// 初始创建基础键盘布局
createKeyboardLayout(baseKeys);

// 添加切换到功能键布局的按钮
const functionKeyButton = document.createElement('button');
functionKeyButton.textContent = '功能键';
functionKeyButton.addEventListener('click', () => {
    virtualKeyboard.innerHTML = '';
    createKeyboardLayout(functionKeys);
});
virtualKeyboard.appendChild(functionKeyButton);

// 添加切换到符号键布局的按钮
const symbolKeyButton = document.createElement('button');
symbolKeyButton.textContent = '符号键';
symbolKeyButton.addEventListener('click', () => {
    virtualKeyboard.innerHTML = '';
    createKeyboardLayout(symbolKeys);
});
virtualKeyboard.appendChild(symbolKeyButton);

// 添加切换回基础布局的按钮
const baseKeyButton = document.createElement('button');
baseKeyButton.textContent = '基础键';
baseKeyButton.addEventListener('click', () => {
    virtualKeyboard.innerHTML = '';
    createKeyboardLayout(baseKeys);
});
virtualKeyboard.appendChild(baseKeyButton);

// 表单提交事件
function handleRdpFormSubmit(event) {
    event.preventDefault();
    const serverAddress = document.getElementById('serverAddress').value.trim();
    const serverPort = document.getElementById('serverPort').value? document.getElementById('serverPort').value.trim() : 3389;
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value.trim();

    // 清空错误消息
    errorMessages.innerHTML = '';

    // 验证输入
    if (!serverAddress) {
        errorMessages.innerHTML += '<p>服务器地址不能为空。</p>';
        return;
    }

    connectWebSocket(serverAddress, serverPort, username, password);
}
rdpForm.addEventListener('submit', handleRdpFormSubmit);

// 其他功能相关事件处理（如断开连接、粘贴、分辨率更改、全屏等）
// 断开连接按钮点击事件
function handleDisconnectButtonClick() {
    if (ws) {
        ws.close();
    }
}
disconnectButton.addEventListener('click', handleDisconnectButtonClick);
disconnectButtonFloat.addEventListener('click', handleDisconnectButtonClick);

// 粘贴按钮点击事件
async function handlePasteButtonClick() {
    if (navigator.clipboard) {
        try {
            const text = await navigator.clipboard.readText();
            if (ws) {
                ws.send(JSON.stringify({ type: 'paste', text: text }));
            }
        } catch (err) {
            console.error('获取剪贴板内容失败:', err);
        }
    } else {
        console.error('您的浏览器不支持Clipboard API，请升级浏览器以使用粘贴功能。');
    }
}
pasteButton.addEventListener('click', handlePasteButtonClick);
pasteButtonFloat.addEventListener('click', handlePasteButtonClick);

// 分辨率更改按钮点击事件
function handleResolutionButtonClick() {
    if (ws) {
        const newWidth = window.innerWidth;
        const newHeight = window.innerHeight;
        loadingOverlay.style.display = 'flex';
        ws.send(JSON.stringify({ type:'resolution', width: newWidth, height: newHeight }));
    }
}
resolutionButton.addEventListener('click', handleResolutionButtonClick);
resolutionButtonFloat.addEventListener('click', handleResolutionButtonClick);

// 全屏功能
function enterFullscreen() {
    if (canvas.requestFullscreen) {
        canvas.requestFullscreen();
        floatBall.style.display = 'block';
    } else if (canvas.webkitRequestFullscreen) {
        canvas.webkitRequestFullscreen();
        floatBall.style.display = 'block';
    } else if (canvas.mozRequestFullScreen) {
        canvas.mozRequestFullScreen();
        floatBall.style.display = 'block';
    } else if (canvas.msRequestFullscreen) {
        canvas.msRequestFullscreen();
        floatBall.style.display = 'block';
    }
}

function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
        floatBall.style.display = 'none';
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
        floatBall.style.display = 'none';
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
        floatBall.style.display = 'none';
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
        floatBall.style.display = 'none';
    }
}

function handleKeydownForFullscreen(event) {
    if (event.key === 'F11') {
        enterFullscreen();
    } else if (event.key === 'Escape') {
        exitFullscreen();
    }
}
window.addEventListener('keydown', handleKeydownForFullscreen);

exitFullscreenButton.addEventListener('click', () => {
    exitFullscreen();
});

// 当虚拟键盘隐藏时，恢复页面的padding
virtualKeyboard.addEventListener('hidden', () => {
    document.body.style.paddingBottom = '0px';
});
